package org.example.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration /*声明该类为核心配置类*/
@PropertySource("classpath:db.properties")
@MapperScan("org.example.dao")
@ComponentScan("org.example")
public class SpringConfig {
     @Value("${jdbc.driver}")
     private String driver;
     @Value("${jdbc.url}")
     private String url;
     @Value("${jdbc.username}")
     private String username;
     @Value("${jdbc.password}")
     private String password;


     @Bean
     public DataSource getDataSource() {
         //创建数据源对象
         DruidDataSource dataSource = new DruidDataSource();
         dataSource.setDriverClassName(driver);
         dataSource.setUrl(url);
         dataSource.setUsername(username);
         dataSource.setPassword(password);
         return dataSource;
     }

     @Bean
     public SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource) throws IOException {
         SqlSessionFactoryBean factoryBaen = new SqlSessionFactoryBean();
         factoryBaen.setDataSource(dataSource);

         factoryBaen.setTypeAliasesPackage("org.org.example.model");
         factoryBaen.setMapperLocations(new PathMatchingResourcePatternResolver()
                 .getResources("classpath:mapper/*.xml"));
         return factoryBaen;
     }






}
